package com.ysd.lis.service.bac.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysParamSearchOutputDto;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.request.bac.BacDrugResTempQuickInsertRequest;
import com.ysd.lis.service.bac.BacDrugTestResultService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cfz
 * @since 2024-03-21
 */
@Service
public class BacDrugTestResultServiceImpl extends ServiceImpl<BacDrugTestResultMapper, BacDrugTestResult> implements BacDrugTestResultService {

    @Autowired
    BacDrugTestResultMapper bacDrugTestResultMapper;
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    BacDrugResultTempdetailMapper bacDrugResultTempdetailMapper;
    @Autowired
    BacBreakPointCalcServiceImpl bacBreakPointCalcService;
    @Autowired
    BacAstTestMthDictMapper bacAstTestMthDictMapper;
    @Autowired
    BacTestResultMapper bacTestResultMapper;

    @Override
    public Result findBacDrugTestResultList(BacDrugTestResult bacDrugTestResult) {
        List<BacDrugTestResult> list = findBacDrugTestResultArray(bacDrugTestResult);
        return Result.succ(1, "请求成功", list);
    }

    @Override
    public List<BacDrugTestResult> findBacDrugTestResultArray(BacDrugTestResult bacDrugTestResult) {
        MPJLambdaWrapper<BacDrugTestResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(BacDrugTestResult.class);
        queryWrapper.selectAs("drugTestMth", BacAstTestMthDict::getName, BacDrugTestResult::getDrugTestMethNa);
        queryWrapper.selectAs("interp", BacInterpretationCodeDict::getName, BacDrugTestResult::getInterpNa);
        queryWrapper.selectAs("interp", BacInterpretationCodeDict::getDisplayColor, BacDrugTestResult::getInterpDisplayColor);
        queryWrapper.selectAs("ant", BacAntibioticsDict::getVerificationPrice, BacDrugTestResult::getVerificationPrice);

        queryWrapper.eq(BacDrugTestResult::getDelFlag, 0);
        if (!BeanUtil.isEmpty(bacDrugTestResult.getSampleda())) {
            Timestamp startTime = Timestamp.valueOf(bacDrugTestResult.getSampleda().toString().substring(0, 10) + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(bacDrugTestResult.getSampleda().toString().substring(0, 10) + " 23:59:59");
            queryWrapper.ge(BacDrugTestResult::getSampleda, startTime);
            queryWrapper.le(BacDrugTestResult::getSampleda, endTime);
        }

        queryWrapper.eq(BacDrugTestResult::getRptGroup, bacDrugTestResult.getRptGroup());
        queryWrapper.eq(BacDrugTestResult::getSampleNo, bacDrugTestResult.getSampleNo());
        //queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getMaininfoId()), BacDrugTestResult::getMaininfoId, bacDrugTestResult.getMaininfoId());
        queryWrapper.eq(BacDrugTestResult::getTestFlowNo, bacDrugTestResult.getTestFlowNo());
        queryWrapper.eq(BacDrugTestResult::getTestNodeNo, bacDrugTestResult.getTestNodeNo());
//        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getBacTestResultId()), BacDrugTestResult::getBacTestResultId, bacDrugTestResult.getBacTestResultId());
        queryWrapper.eq(BacDrugTestResult::getIsolateNum, bacDrugTestResult.getIsolateNum());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getAntNo()), BacDrugTestResult::getAntNo, bacDrugTestResult.getAntNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getAntNa()), BacDrugTestResult::getAntNa, bacDrugTestResult.getAntNa());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getTestResult()), BacDrugTestResult::getTestResult, bacDrugTestResult.getTestResult());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getDrugMthNo()), BacDrugTestResult::getDrugMthNo, bacDrugTestResult.getDrugMthNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getAntRecomGroupId()), BacDrugTestResult::getAntRecomGroupId, bacDrugTestResult.getAntRecomGroupId());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getTestResult()), BacDrugTestResult::getTestResult, bacDrugTestResult.getTestResult());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getBreakPoint()), BacDrugTestResult::getBreakPoint, bacDrugTestResult.getBreakPoint());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getItemDictNo()), BacDrugTestResult::getItemDictNo, bacDrugTestResult.getItemDictNo());

        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getSensitiveNo()), BacDrugTestResult::getSensitiveNo, bacDrugTestResult.getSensitiveNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getSeq()), BacDrugTestResult::getSeq, bacDrugTestResult.getSeq());
        queryWrapper.eq(!BeanUtil.isEmpty(bacDrugTestResult.getIsReport()), BacDrugTestResult::getIsReport, bacDrugTestResult.getIsReport());
        queryWrapper.eq(!BeanUtil.isEmpty(bacDrugTestResult.getIsNaturlResis()), BacDrugTestResult::getIsNaturlResis, bacDrugTestResult.getIsNaturlResis());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getBreakPointId()), BacDrugTestResult::getBreakPointId, bacDrugTestResult.getBreakPointId());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getGuideline()), BacDrugTestResult::getGuideline, bacDrugTestResult.getGuideline());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getYear()), BacDrugTestResult::getYear, bacDrugTestResult.getYear());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getGermCodeType()), BacDrugTestResult::getGermCodeType, bacDrugTestResult.getGermCodeType());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getGermNo()), BacDrugTestResult::getGermNo, bacDrugTestResult.getGermNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getBreakPointType()), BacDrugTestResult::getBreakPointType, bacDrugTestResult.getBreakPointType());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getHost()), BacDrugTestResult::getHost, bacDrugTestResult.getHost());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getWhonetTest()), BacDrugTestResult::getWhonetTest, bacDrugTestResult.getWhonetTest());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getPotency()), BacDrugTestResult::getPotency, bacDrugTestResult.getPotency());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getInfeSite()), BacDrugTestResult::getInfeSite, bacDrugTestResult.getInfeSite());
        queryWrapper.eq(!BeanUtil.isEmpty(bacDrugTestResult.getR()), BacDrugTestResult::getR, bacDrugTestResult.getR());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getI()), BacDrugTestResult::getI, bacDrugTestResult.getI());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getSdd()), BacDrugTestResult::getSdd, bacDrugTestResult.getSdd());
        queryWrapper.eq(!BeanUtil.isEmpty(bacDrugTestResult.getS()), BacDrugTestResult::getS, bacDrugTestResult.getS());
        queryWrapper.eq(!BeanUtil.isEmpty(bacDrugTestResult.getEcoff()), BacDrugTestResult::getEcoff, bacDrugTestResult.getEcoff());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getBreakPointRef()), BacDrugTestResult::getBreakPointRef, bacDrugTestResult.getBreakPointRef());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getRefTable()), BacDrugTestResult::getRefTable, bacDrugTestResult.getRefTable());
        queryWrapper.eq(StringUtils.isNotBlank(bacDrugTestResult.getRefTableSeq()), BacDrugTestResult::getRefTableSeq, bacDrugTestResult.getRefTableSeq());


        queryWrapper.like(StringUtils.isNotBlank(bacDrugTestResult.getRemark1()), BacDrugTestResult::getRemark1, bacDrugTestResult.getRemark1());
        queryWrapper.like(StringUtils.isNotBlank(bacDrugTestResult.getRemark2()), BacDrugTestResult::getRemark2, bacDrugTestResult.getRemark2());
        queryWrapper.like(StringUtils.isNotBlank(bacDrugTestResult.getRemark3()), BacDrugTestResult::getRemark3, bacDrugTestResult.getRemark3());
        queryWrapper.like(StringUtils.isNotBlank(bacDrugTestResult.getRemark4()), BacDrugTestResult::getRemark4, bacDrugTestResult.getRemark4());
        queryWrapper.leftJoin(BacAstTestMthDict.class, "drugTestMth", p -> p.eq(BacAstTestMthDict::getCode, BacDrugTestResult::getDrugMthNo).eq(BacAstTestMthDict::getDelFlag, 0));
        queryWrapper.leftJoin(BacInterpretationCodeDict.class, "interp", p -> p.eq(BacInterpretationCodeDict::getCode, BacDrugTestResult::getSensitiveNo).eq(BacInterpretationCodeDict::getDelFlag, 0));
        queryWrapper.leftJoin(BacAntibioticsDict.class, "ant", p -> p.eq(BacAntibioticsDict::getAntCode, BacDrugTestResult::getAntNo).isNotNull(BacAntibioticsDict::getAntCode).ne(BacAntibioticsDict::getAntCode, ""));
//        queryWrapper.orderByAsc(BacDrugTestResult::getAntRecomGroupId);
//        queryWrapper.orderByAsc(BacDrugTestResult::getSeq);
        //queryWrapper.orderByAsc(BacDrugTestResult::getDrugMthNo).orderByAsc(BacAntibioticsDict::getClsiOrder);

        List<BacDrugTestResult> bacDrugTestResultList = bacDrugTestResultMapper.selectList(queryWrapper);
        List<BacDrugTestResult> collect1 = bacDrugTestResultList.stream()
                .sorted(Comparator.comparing(BacDrugTestResult::getDrugMthNo)
                        .thenComparing(bacResult -> {
                            if (StringUtils.isBlank(bacResult.getSeq())) {
                                return Integer.MAX_VALUE;
                            }
                            return Integer.parseInt(bacResult.getSeq());
                        }))
                .collect(Collectors.toList());

        return collect1;
    }

    @Override
    public Result addBacDrugTestResult(BacDrugTestResult bacDrugTestResult) {
        //判断是否是不出报告的药敏
        //先查出上机记录
        String format = DateUtil.format(bacDrugTestResult.getSampleda(), "yyyy-MM-dd");
        Timestamp startTime1 = Timestamp.valueOf(format + " 00:00:00");
        Timestamp endTime1 = Timestamp.valueOf(format + " 23:59:59");
        LambdaQueryWrapper<LabMaininfo> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(LabMaininfo::getDelFlag, 0)
                .eq(LabMaininfo::getRptGroup, bacDrugTestResult.getRptGroup())
                            .ge(LabMaininfo::getSampleda, startTime1)
                            .le(LabMaininfo::getSampleda, endTime1)
                .eq(LabMaininfo::getSampleNo, bacDrugTestResult.getSampleNo())
                .eq(LabMaininfo::getOrgId, bacDrugTestResult.getOrgId());
        List<LabMaininfo> maininfoList1 = labMaininfoMapper.selectList(queryWrapper3);
        String notReportSensitiveNo = null;
        if (ToolsUtils.isNotEmpty(maininfoList1)) {
            LabMaininfo labMaininfo = maininfoList1.get(0);
            if(ToolsUtils.isNotEmpty(labMaininfo)){
                notReportSensitiveNo = judgeDrugNotReport(bacDrugTestResult,labMaininfo);
            }
        }

        //判断是否符合天然耐药规则
        judgeNaturalMdrRule(bacDrugTestResult);
        Integer isNaturlResis = bacDrugTestResult.getIsNaturlResis();
        //1是天然耐药
        if(!(ToolsUtils.isNotEmpty(isNaturlResis)&&isNaturlResis==1)&&ToolsUtils.isEmpty(notReportSensitiveNo)){
            //查看此结果是否符合药敏结果敏感性规则
            String sensitiveNo = judgeSensitiveResultRule(bacDrugTestResult,true);
            if(ToolsUtils.isEmpty(sensitiveNo)){
                /*计算折点、每次修改都会重新计算折点*/
                if (ToolsUtils.isNotEmpty(bacDrugTestResult.getDrugMthNo()) && ToolsUtils.isNotEmpty(bacDrugTestResult.getBreakPoint()) && false) {
                    StringBuilder formattedASTResult = new StringBuilder();
                    BigDecimal[] result = new BigDecimal[1];
                    boolean res = bacBreakPointCalcService.transResult(bacDrugTestResult.getTestResult(), formattedASTResult, result);
                    if (res) {
                        /*检测方法*/
                        LambdaQueryWrapper<BacAstTestMthDict> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(BacAstTestMthDict::getDelFlag, 0);
                        queryWrapper.eq(BacAstTestMthDict::getCode, bacDrugTestResult.getDrugMthNo());
                        List<BacAstTestMthDict> astTestMthDictList = bacAstTestMthDictMapper.selectList(queryWrapper);
                        if (ToolsUtils.isNotEmpty(astTestMthDictList)) {
                            /*折点对象*/
                            BacBreakPoint bacBreakPoint = new BacBreakPoint();
                            bacBreakPoint.setR(ToolsUtils.isNotEmpty(bacDrugTestResult.getR()) ? bacDrugTestResult.getR().toString() : "");
                            bacBreakPoint.setS(ToolsUtils.isNotEmpty(bacDrugTestResult.getS()) ? bacDrugTestResult.getS().toString() : "");
                            bacBreakPoint.setI(ToolsUtils.isNotEmpty(bacDrugTestResult.getI()) ? bacDrugTestResult.getI().toString() : "");
                            bacBreakPoint.setEcvEcoff(ToolsUtils.isNotEmpty(bacDrugTestResult.getEcoff()) ? bacDrugTestResult.getEcoff().toString() : "");
                            bacBreakPoint.setSdd(ToolsUtils.isNotEmpty(bacDrugTestResult.getSdd()) ? bacDrugTestResult.getSdd().toString() : "");
                            BacInterpretationCodeDict ic = bacBreakPointCalcService.getInterpretationCode(astTestMthDictList.get(0), result[0], bacBreakPoint);
                            if (ic != null) {
                                bacDrugTestResult.setSensitiveNo(ToolsUtils.isNotEmpty(ic.getCode()) ? ic.getCode() : "");
                                bacDrugTestResult.setInterpNa(ToolsUtils.isNotEmpty(ic.getName()) ? ic.getName() : "");
                                bacDrugTestResult.setInterpDisplayColor(ToolsUtils.isNotEmpty(ic.getDisplayColor()) ? ic.getDisplayColor() : "");
                            }
                        }
                    }
                } else {
                    /*查询出细菌结果*/
                    LambdaQueryWrapper<BacTestResult> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(BacTestResult::getDelFlag, 0);
                    if (ToolsUtils.isNotEmpty(bacDrugTestResult.getSampleda())) {
                        Timestamp timestamp = new Timestamp(bacDrugTestResult.getSampleda().getTime());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String formattedDate = sdf.format(timestamp);
                        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
                        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
                        queryWrapper.ge(BacTestResult::getSampleda, startTime);
                        queryWrapper.le(BacTestResult::getSampleda, endTime);
                    }
                    queryWrapper.eq(BacTestResult::getIsolateNum, bacDrugTestResult.getIsolateNum());
                    queryWrapper.eq(BacTestResult::getGermNo, bacDrugTestResult.getGermNo());
                    queryWrapper.eq(BacTestResult::getRptGroup, bacDrugTestResult.getRptGroup());
                    queryWrapper.eq(BacTestResult::getSampleNo, bacDrugTestResult.getSampleNo());
                    queryWrapper.eq(ToolsUtils.isNotEmpty(bacDrugTestResult.getTestFlowNo()), BacTestResult::getTestFlowNo, bacDrugTestResult.getTestFlowNo());
                    queryWrapper.eq(ToolsUtils.isNotEmpty(bacDrugTestResult.getTestNodeNo()), BacTestResult::getTestNodeNo, bacDrugTestResult.getTestNodeNo());
                    List<BacTestResult> testResultList = bacTestResultMapper.selectList(queryWrapper);
                    if (ToolsUtils.isNotEmpty(testResultList)) {
                        List<BacDrugTestResult> astResults = new ArrayList<>();
                        astResults.add(bacDrugTestResult);
                        boolean isCalcBP = false;/*重新赋值折点*/
                        boolean isCalcIC = false;/*重新计算敏感性*/
                        if (ToolsUtils.isNotEmpty(bacDrugTestResult.getDataFrom()) && "2".equals(bacDrugTestResult.getDataFrom())) {
                            isCalcBP = true;
                            isCalcIC = true;
                        } else if (ToolsUtils.isNotEmpty(bacDrugTestResult.getDataFrom()) && "1".equals(bacDrugTestResult.getDataFrom())) {
                            if (ToolsUtils.isNotEmpty(bacDrugTestResult.getIsBpFromInstr()) && bacDrugTestResult.getIsBpFromInstr().equals(1)) {
                                isCalcBP = false;
                            }
                            isCalcIC = false;
                        }
                        bacBreakPointCalcService.setApplicableBreakpoint(testResultList.get(0), astResults, isCalcBP, isCalcIC);
                    }
                }

            }
        }
        int i = bacDrugTestResultMapper.insert(bacDrugTestResult);
        if (i > 0) {
            return Result.succ(1, "新增成功", bacDrugTestResult);
        }
        return Result.fail("新增失败");
    }

    @Autowired
    BacAntibioticsDictMapper bacAntibioticsDictMapper;
    @Autowired
    BacNaturalMdrRuleMapper bacNaturalMdrRuleMapper;
    @Override
    public void judgeNaturalMdrRule(BacDrugTestResult bacDrugTestResult) {
        String antNo = bacDrugTestResult.getAntNo();
        //先根据抗生素查出抗生素字典
        MPJLambdaWrapper<BacAntibioticsDict> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(BacAntibioticsDict::getAntCode, antNo).eq(BacAntibioticsDict::getDelFlag, 0);

        List<BacAntibioticsDict> bacAntibioticsDicts = bacAntibioticsDictMapper.selectList(lambdaQueryWrapper);
        if(ToolsUtils.isNotEmpty(bacAntibioticsDicts)){
            BacAntibioticsDict bacAntibioticsDict = bacAntibioticsDicts.get(0);
            //查出抗生素的分类和子分类
            String antClassNo = bacAntibioticsDict.getAntClassNo();
            String subClassNo = bacAntibioticsDict.getSubClassNo();
            String germNo = bacDrugTestResult.getGermNo();
            //根据细菌，抗生素的分类和子分类和编号查出对应的天然耐药规则
            MPJLambdaWrapper<BacNaturalMdrRule> queryWrapper = new MPJLambdaWrapper<>();

            queryWrapper.eq(BacNaturalMdrRule::getGermNo, germNo)
                    .eq(BacNaturalMdrRule::getDelFlag,0)
                    .and(p->p.eq(BacNaturalMdrRule::getAntNo,antNo)
                            .or().eq(ToolsUtils.isNotEmpty(subClassNo),BacNaturalMdrRule::getSubClassNo,subClassNo)
                            .or().eq(ToolsUtils.isNotEmpty(antClassNo),BacNaturalMdrRule::getAntClassNo,antClassNo));
            Integer cnt = bacNaturalMdrRuleMapper.selectCount(queryWrapper);
            if(cnt>0){
                bacDrugTestResult.setIsNaturlResis(1);
                bacDrugTestResult.setSensitiveNo("*");
                bacDrugTestResult.setInterpNa("*");
                bacDrugTestResult.setSensitiveFrom("天然耐药");
                bacDrugTestResult.setBreakPoint("");
                bacDrugTestResult.setBreakPointId("");
                bacDrugTestResult.setYear("");
                bacDrugTestResult.setGuideline("");
                bacDrugTestResult.setBreakPointType("");
                bacDrugTestResult.setHost("");
                bacDrugTestResult.setWhonetTest("");
                bacDrugTestResult.setR(null);
                bacDrugTestResult.setI("");
                bacDrugTestResult.setS(null);
                bacDrugTestResult.setBreakPointRef("");
                bacDrugTestResult.setRefTable("");
                bacDrugTestResult.setSpeciesGroup("");
                //如果是天然耐药的贼需要设置是否报告设置成0
                //bacDrugTestResult.setIsReport(0);
            }else {
                bacDrugTestResult.setIsNaturlResis(0);
                //bacDrugTestResult.setSensitiveNo("");
            }

        }
    }

    @Autowired
    BacSensitiveResultRuleMapper bacSensitiveResultRuleMapper;
    @Override
    public String judgeSensitiveResultRule(BacDrugTestResult bacDrugTestResult,boolean isCalcIC) {
        String testResult = bacDrugTestResult.getTestResult();
        if(ToolsUtils.isNotEmpty(testResult)){
            //先根据结果查药敏结果敏感性规则
            MPJLambdaWrapper<BacSensitiveResultRule> lambdaQueryWrapper = new MPJLambdaWrapper<>();
            lambdaQueryWrapper.selectAll(BacSensitiveResultRule.class)
                    .selectAs(BacInterpretationCodeDict::getName, BacSensitiveResultRule::getSensitiveNa)
                    .selectAs(BacInterpretationCodeDict::getDisplayColor, BacSensitiveResultRule::getDisplayColor)
                    .leftJoin(BacInterpretationCodeDict.class, "sa",
                            p -> p.eq(BacInterpretationCodeDict::getCode, BacSensitiveResultRule::getSensitiveNo).eq(BacInterpretationCodeDict::getDelFlag, 0))
                    .eq(BacSensitiveResultRule::getTestResult, testResult)
                    .eq(BacSensitiveResultRule::getDelFlag, 0);
            List<BacSensitiveResultRule> sensitiveResultRuleList = bacSensitiveResultRuleMapper.selectList(lambdaQueryWrapper);

            String dataFrom = bacDrugTestResult.getDataFrom();
            if(ToolsUtils.isNotEmpty(sensitiveResultRuleList)){
                //如果是仪器数据，则判断系统参数 是否重新计算敏感性 ，如果是0 则不去计算敏感性，如果是1 则重新计算敏感性 并且需要返回敏感性
                BacSensitiveResultRule bacSensitiveResultRule = sensitiveResultRuleList.get(0);
                if("2".equals(dataFrom)||("1".equals(dataFrom)&&isCalcIC)){
                    bacDrugTestResult.setSensitiveNo(bacSensitiveResultRule.getSensitiveNo());
                    bacDrugTestResult.setSensitiveFrom("结果转换");
                    bacDrugTestResult.setInterpNa(bacSensitiveResultRule.getSensitiveNa());
                    bacDrugTestResult.setInterpDisplayColor(bacSensitiveResultRule.getDisplayColor());
                    bacDrugTestResult.setBreakPoint("");
                    bacDrugTestResult.setBreakPointId(bacSensitiveResultRule.getId());
                    bacDrugTestResult.setYear("");
                    bacDrugTestResult.setGuideline("");
                    bacDrugTestResult.setBreakPointType("");
                    bacDrugTestResult.setHost("");
                    bacDrugTestResult.setWhonetTest("");
                    bacDrugTestResult.setR(null);
                    bacDrugTestResult.setI("");
                    bacDrugTestResult.setS(null);
                    bacDrugTestResult.setBreakPointRef("");
                    bacDrugTestResult.setRefTable("");
                    bacDrugTestResult.setSpeciesGroup("");
                }
                return  bacSensitiveResultRule.getSensitiveNo();
            }else {
                if("2".equals(dataFrom)||("1".equals(dataFrom)&&isCalcIC)){
                    bacDrugTestResult.setSensitiveNo("");
                    bacDrugTestResult.setInterpNa("");
                    bacDrugTestResult.setInterpDisplayColor("");
                    bacDrugTestResult.setBreakPoint("");
                    bacDrugTestResult.setBreakPointId("");
                    bacDrugTestResult.setYear("");
                    bacDrugTestResult.setGuideline("");
                    bacDrugTestResult.setBreakPointType("");
                    bacDrugTestResult.setHost("");
                    bacDrugTestResult.setWhonetTest("");
                    bacDrugTestResult.setR(null);
                    bacDrugTestResult.setI("");
                    bacDrugTestResult.setS(null);
                    bacDrugTestResult.setBreakPointRef("");
                    bacDrugTestResult.setRefTable("");
                    bacDrugTestResult.setSpeciesGroup("");
                    bacDrugTestResult.setSensitiveFrom("");
                }
                return null;
            }
        }else {
            return null;
        }

    }

    @Autowired
    BacDrugResultSenroleMapper bacDrugResultSenroleMapper;
    @Autowired
    BacDrugResultSenroleDetailsMapper bacDrugResultSenroleDetailsMapper;
    @Override
    public void judgeResultSenroleRule(BacDrugTestResult bacDrugTestResult, boolean isCalcIC) {
        //如果dataFrom为2（手工录入）或者dataFrom为1（仪器数据）并且isCalcIC(是否从新计算敏感性)为true 则需要重新按照规则计算敏感性
        if("2".equals(bacDrugTestResult.getDataFrom())||("1".equals(bacDrugTestResult.getDataFrom())&&isCalcIC)){
            String antNo = bacDrugTestResult.getAntNo();
            if(ToolsUtils.isNotEmpty(antNo)){
                //查出药敏结果敏感性规则
                MPJLambdaWrapper<BacDrugResultSenrole> queryResultSenroleWrapper = new MPJLambdaWrapper<>();
                queryResultSenroleWrapper.selectAll(BacDrugResultSenrole.class)
                        .selectAs(BacInterpretationCodeDict::getName, BacDrugResultSenrole::getSensitiveNa)
                        .selectAs(BacInterpretationCodeDict::getDisplayColor, BacDrugResultSenrole::getDisplayColor)
                        .leftJoin(BacInterpretationCodeDict.class, "sa",
                                p -> p.eq(BacInterpretationCodeDict::getCode, BacDrugResultSenrole::getSensitiveNo).eq(BacInterpretationCodeDict::getDelFlag, 0));
                queryResultSenroleWrapper.eq(BacDrugResultSenrole::getDelFlag, 0)
                        .eq(BacDrugResultSenrole::getAntNo, antNo);
                List<BacDrugResultSenrole> ruleList = bacDrugResultSenroleMapper.selectList(queryResultSenroleWrapper);
                if(ToolsUtils.isNotEmpty(ruleList)){
                    //取出rulelist中的所有rolecode集合
                    List<String> roleCodeList = ruleList.stream().map(BacDrugResultSenrole::getRoleCode).collect(Collectors.toList());
                    //根据rolecode集合查出所有规则明细
                    MPJLambdaWrapper<BacDrugResultSenroleDetails> querySenroleDetailWrapper = new MPJLambdaWrapper<>();
                    querySenroleDetailWrapper.selectAll(BacDrugResultSenroleDetails.class)
                            .eq(BacDrugResultSenroleDetails::getDelFlag, 0)
                            .in(BacDrugResultSenroleDetails::getRoleCode, roleCodeList);
                    List<BacDrugResultSenroleDetails> senroleDetailList = bacDrugResultSenroleDetailsMapper.selectList(querySenroleDetailWrapper);
                    if(ToolsUtils.isNotEmpty(senroleDetailList)){
                        //获取senroleDetailsList中所有的antno
                        List<String> antNoList = senroleDetailList.stream().map(BacDrugResultSenroleDetails::getAntNo).collect(Collectors.toList());
                        //查出所有的antno对应的结果
                        MPJLambdaWrapper<BacDrugTestResult> queryResultWrapper = new MPJLambdaWrapper<>();
                        queryResultWrapper.selectAll(BacDrugTestResult.class);
                        queryResultWrapper.eq(BacDrugTestResult::getDelFlag, 0);
                        if (!BeanUtil.isEmpty(bacDrugTestResult.getSampleda())) {
                            Timestamp startTime = Timestamp.valueOf(bacDrugTestResult.getSampleda().toString().substring(0, 10) + " 00:00:00");
                            Timestamp endTime = Timestamp.valueOf(bacDrugTestResult.getSampleda().toString().substring(0, 10) + " 23:59:59");
                            queryResultWrapper.ge(BacDrugTestResult::getSampleda, startTime);
                            queryResultWrapper.le(BacDrugTestResult::getSampleda, endTime);
                        }
                        queryResultWrapper.eq(BacDrugTestResult::getRptGroup, bacDrugTestResult.getRptGroup());
                        queryResultWrapper.eq(BacDrugTestResult::getSampleNo, bacDrugTestResult.getSampleNo());
                        queryResultWrapper.eq(BacDrugTestResult::getTestFlowNo, bacDrugTestResult.getTestFlowNo());
                        queryResultWrapper.eq(BacDrugTestResult::getTestNodeNo, bacDrugTestResult.getTestNodeNo());
                        queryResultWrapper.eq(BacDrugTestResult::getIsolateNum, bacDrugTestResult.getIsolateNum());
                        queryResultWrapper.eq(BacDrugTestResult::getGermNo, bacDrugTestResult.getGermNo());
                        queryResultWrapper.in(BacDrugTestResult::getAntNo, antNoList);
                        List<BacDrugTestResult> bacDrugTestResultList = bacDrugTestResultMapper.selectList(queryResultWrapper);


                        //根据rolecode分组
                        Map<String, List<BacDrugResultSenroleDetails>> roleCodeMap = senroleDetailList.stream().collect(Collectors.groupingBy(BacDrugResultSenroleDetails::getRoleCode));
                        for (String entry : roleCodeMap.keySet()) {
                            List<BacDrugResultSenroleDetails> detailsList = roleCodeMap.get(entry);
                            Boolean isCalcFlag = true;
                            //循环每组的规则明细
                            for (BacDrugResultSenroleDetails roleDetail : detailsList) {
                                //获取规则的敏感性
                                String roleSensitiveNo = roleDetail.getSensitiveNo();
                                if(ToolsUtils.isNotEmpty(roleSensitiveNo)){
                                    //从药敏结果中查出此药敏的结果
                                    List<BacDrugTestResult> testResultList = bacDrugTestResultList.stream().filter(m -> m.getAntNo().equals(roleDetail.getAntNo())).collect(Collectors.toList());
                                    if(ToolsUtils.isNotEmpty(testResultList)){
                                        BacDrugTestResult testResult = testResultList.get(0);
                                        String testSensitiveNo = testResult.getSensitiveNo();
                                        if(ToolsUtils.isNotEmpty(testSensitiveNo)){
                                            if(!roleSensitiveNo.equals(testSensitiveNo)){
                                                isCalcFlag=false;
                                            }
                                        }else {
                                            isCalcFlag=false;
                                        }
                                    }else {
                                        isCalcFlag=false;
                                    }
                                }else {
                                    isCalcFlag=false;
                                }
                            }
                            if(isCalcFlag){
                                //根据entry 获取规则
                                BacDrugResultSenrole role = ruleList.stream().filter(m -> m.getRoleCode().equals(entry)).collect(Collectors.toList()).get(0);
                                String roleSensitiveNo = role.getSensitiveNo();
                                if(ToolsUtils.isNotEmpty(roleSensitiveNo)){
                                    bacDrugTestResult.setSensitiveNo(roleSensitiveNo);
                                    bacDrugTestResult.setInterpNa(role.getSensitiveNa());
                                    bacDrugTestResult.setInterpDisplayColor(role.getDisplayColor());
                                    bacDrugTestResult.setSensitiveFrom(role.getRoleName());
                                }
                            }

                        }
                    }

                }
            }
        }
    }

    @Autowired
    BacGermDictMapper bacGermDictMapper;
    @Autowired
    BacDrugNotReportMapper bacDrugNotReportMapper;
    @Override
    public String judgeDrugNotReport(BacDrugTestResult bacDrugTestResult, LabMaininfo labMaininfo) {
        String sensitiveNo = null;
        BacDrugNotReport bacDrugNotReport = null;
        //样本分类
        String sampleType = labMaininfo.getSampleType();
        if(ToolsUtils.isNotEmpty(sampleType)){
            //查出抗生素的细菌
            String germNo = bacDrugTestResult.getGermNo();
            String antNo = bacDrugTestResult.getAntNo();
            //根据CODE查出该细菌
            MPJLambdaWrapper<BacGermDict> lambdaQueryWrapper = new MPJLambdaWrapper<>();
            lambdaQueryWrapper.eq(BacGermDict::getGermNo, germNo).eq(BacGermDict::getDelFlag, 0);
            List<BacGermDict> bacGermDicts = bacGermDictMapper.selectList(lambdaQueryWrapper);
            if(ToolsUtils.isNotEmpty(bacGermDicts)){
                BacGermDict bacGermDict = bacGermDicts.get(0);
                //查出该细菌的属
                String genus = bacGermDict.getGenus();
                //根据样本分类，细菌属，细菌编号和抗生素查出对应的不出报告规则
                MPJLambdaWrapper<BacDrugNotReport> queryWrapper = new MPJLambdaWrapper<>();
                queryWrapper.eq(BacDrugNotReport::getSampleType, sampleType)
                        .eq(BacDrugNotReport::getDrugNo, antNo)
                        .eq(BacDrugNotReport::getDelFlag,0)
                        .and(p->p.eq(ToolsUtils.isNotEmpty(genus),BacDrugNotReport::getGenus,genus)
                                .or().eq(ToolsUtils.isNotEmpty(germNo),BacDrugNotReport::getGermNo,germNo));
                List<BacDrugNotReport> bacDrugNotReports = bacDrugNotReportMapper.selectList(queryWrapper);
                if(ToolsUtils.isNotEmpty(bacDrugNotReports)){
                    bacDrugNotReport = bacDrugNotReports.get(0);
                    sensitiveNo = bacDrugNotReport.getSensitiveNo();
                }
            }
        }
        //如果bacDrugNotReport不为空则是不报告项目
        if(ToolsUtils.isNotEmpty(bacDrugNotReport)){
            bacDrugTestResult.setIsReport(0);
        }else {
            bacDrugTestResult.setIsReport(1);
        }
        //如果敏感性值则不需要计算折点和敏感性
        if(ToolsUtils.isNotEmpty(sensitiveNo)){
            bacDrugTestResult.setSensitiveNo(sensitiveNo);
            bacDrugTestResult.setSensitiveFrom("不报告项目");
            bacDrugTestResult.setInterpNa(sensitiveNo);
            bacDrugTestResult.setInterpDisplayColor("");
            bacDrugTestResult.setBreakPoint("");
            bacDrugTestResult.setBreakPointId("");
            bacDrugTestResult.setYear("");
            bacDrugTestResult.setGuideline("");
            bacDrugTestResult.setBreakPointType("");
            bacDrugTestResult.setHost("");
            bacDrugTestResult.setWhonetTest("");
            bacDrugTestResult.setR(null);
            bacDrugTestResult.setI("");
            bacDrugTestResult.setS(null);
            bacDrugTestResult.setBreakPointRef("");
            bacDrugTestResult.setRefTable("");
            bacDrugTestResult.setSpeciesGroup("");
        }

        return sensitiveNo;
    }

    @Override
    public Result drugTestResultIsReportChange(BacDrugTestResult bacTestResult) {
        int i = bacDrugTestResultMapper.updateById(bacTestResult);
        if (i > 0) {
            return Result.succ(1, "更新成功", bacTestResult);
        }else {
            return Result.fail("更新失败");
        }
    }

    @Override
    public Result deleteBacDrugTestResult(BacDrugTestResult bacDrugTestResult) {
        bacDrugTestResult.setDelFlag(1);
        int i = bacDrugTestResultMapper.updateById(bacDrugTestResult);
        if (i > 0) {
            return Result.succ(1, "删除成功", bacDrugTestResult);
        }
        return Result.fail("删除失败");
    }

    @Override
    public Result batchDeleteBacDrugTestResult(List<BacDrugTestResult> bacDrugTestResults) {
        for (BacDrugTestResult m : bacDrugTestResults) {
            m.setDelFlag(1);
        }
        boolean r = this.updateBatchById(bacDrugTestResults);
        return r ? Result.succ(1, "删除成功", bacDrugTestResults) : Result.fail("删除失败");
    }

    @Override
    public Result updateBacDrugTestResult(BacDrugTestResult bacDrugTestResult) {
        //判断是否是不出报告的药敏
        //先查出上机记录
        String format = DateUtil.format(bacDrugTestResult.getSampleda(), "yyyy-MM-dd");
        Timestamp startTime1 = Timestamp.valueOf(format + " 00:00:00");
        Timestamp endTime1 = Timestamp.valueOf(format + " 23:59:59");
        LambdaQueryWrapper<LabMaininfo> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(LabMaininfo::getDelFlag, 0)
                .eq(LabMaininfo::getRptGroup, bacDrugTestResult.getRptGroup())
                .ge(LabMaininfo::getSampleda, startTime1)
                .le(LabMaininfo::getSampleda, endTime1)
                .eq(LabMaininfo::getSampleNo, bacDrugTestResult.getSampleNo())
                .eq(LabMaininfo::getOrgId, bacDrugTestResult.getOrgId());
        List<LabMaininfo> maininfoList1 = labMaininfoMapper.selectList(queryWrapper3);
        String notReportSensitiveNo = null;
        if (ToolsUtils.isNotEmpty(maininfoList1)) {
            LabMaininfo labMaininfo = maininfoList1.get(0);
            if(ToolsUtils.isNotEmpty(labMaininfo)){
                //不报告项目规则,如果有敏感性默认值，则不需要计算折点和敏感性
                notReportSensitiveNo = judgeDrugNotReport(bacDrugTestResult, labMaininfo);
            }
        }

        //判断是否符合天然耐药规则
        judgeNaturalMdrRule(bacDrugTestResult);
        Integer isNaturlResis = bacDrugTestResult.getIsNaturlResis();
        //1是天然耐药
        if(!(ToolsUtils.isNotEmpty(isNaturlResis)&&isNaturlResis==1)&&ToolsUtils.isEmpty(notReportSensitiveNo)){

            boolean isCalcBP = false;/*重新赋值折点*/
            boolean isCalcIC = false;/*重新计算敏感性*/
            if (ToolsUtils.isNotEmpty(bacDrugTestResult.getDataFrom()) && "2".equals(bacDrugTestResult.getDataFrom())) {
                isCalcBP = true;
                isCalcIC = true;
            } else if (ToolsUtils.isNotEmpty(bacDrugTestResult.getDataFrom()) && "1".equals(bacDrugTestResult.getDataFrom())) {
                if (ToolsUtils.isNotEmpty(bacDrugTestResult.getIsBpFromInstr()) && bacDrugTestResult.getIsBpFromInstr().equals(1)) {
                    isCalcBP = false;
                }
                isCalcIC = false;

                try {
                    SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(bacDrugTestResult.getOrgId(), "instrDataIsCalcBP", bacDrugTestResult.getRptGroup(), null);
                    String wswymbgsfhbbg = paramResult.getValueStr();
                    if (ToolsUtils.isNotEmpty(wswymbgsfhbbg) && "1".equals(wswymbgsfhbbg)) {
                        isCalcBP = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(bacDrugTestResult.getOrgId(), "instrDataIsCalcIC", bacDrugTestResult.getRptGroup(), null);
                    String wswymbgsfhbbg = paramResult.getValueStr();
                    if (ToolsUtils.isNotEmpty(wswymbgsfhbbg) && "1".equals(wswymbgsfhbbg)) {
                        isCalcIC = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            //查看此结果是否符合药敏结果转换规则
            String sensitiveNo = judgeSensitiveResultRule(bacDrugTestResult,isCalcIC);
            if(ToolsUtils.isEmpty(sensitiveNo)){
                /*计算折点*/
                if (ToolsUtils.isNotEmpty(bacDrugTestResult.getDrugMthNo())
                        && ToolsUtils.isNotEmpty(bacDrugTestResult.getBreakPoint())
                        && ToolsUtils.isNotEmpty(bacDrugTestResult.getDataFrom())
                        && !"1".equals(bacDrugTestResult.getDataFrom())
                        && false) {
                    /*只计算敏感性*/
                    StringBuilder formattedASTResult = new StringBuilder();
                    BigDecimal[] result = new BigDecimal[1];
                    boolean res = bacBreakPointCalcService.transResult(bacDrugTestResult.getTestResult(), formattedASTResult, result);
                    if (res) {
                        /*检测方法*/
                        LambdaQueryWrapper<BacAstTestMthDict> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(BacAstTestMthDict::getDelFlag, 0);
                        queryWrapper.eq(BacAstTestMthDict::getCode, bacDrugTestResult.getDrugMthNo());
                        List<BacAstTestMthDict> astTestMthDictList = bacAstTestMthDictMapper.selectList(queryWrapper);
                        if (ToolsUtils.isNotEmpty(astTestMthDictList)) {
                            /*折点对象*/
                            BacBreakPoint bacBreakPoint = new BacBreakPoint();
                            bacBreakPoint.setR(ToolsUtils.isNotEmpty(bacDrugTestResult.getR()) ? bacDrugTestResult.getR().toString() : "");
                            bacBreakPoint.setS(ToolsUtils.isNotEmpty(bacDrugTestResult.getS()) ? bacDrugTestResult.getS().toString() : "");
                            bacBreakPoint.setI(ToolsUtils.isNotEmpty(bacDrugTestResult.getI()) ? bacDrugTestResult.getI().toString() : "");
                            bacBreakPoint.setEcvEcoff(ToolsUtils.isNotEmpty(bacDrugTestResult.getEcoff()) ? bacDrugTestResult.getEcoff().toString() : "");
                            bacBreakPoint.setSdd(ToolsUtils.isNotEmpty(bacDrugTestResult.getSdd()) ? bacDrugTestResult.getSdd().toString() : "");
                            BacInterpretationCodeDict ic = bacBreakPointCalcService.getInterpretationCode(astTestMthDictList.get(0), result[0], bacBreakPoint);
                            if (ic != null) {
                                bacDrugTestResult.setSensitiveNo(ToolsUtils.isNotEmpty(ic.getCode()) ? ic.getCode() : "");
                                bacDrugTestResult.setInterpNa(ToolsUtils.isNotEmpty(ic.getName()) ? ic.getName() : "");
                                bacDrugTestResult.setInterpDisplayColor(ToolsUtils.isNotEmpty(ic.getDisplayColor()) ? ic.getDisplayColor() : "");
                            }
                        }
                    }
                } else {
                    /*查询出细菌结果*/
                    LambdaQueryWrapper<BacTestResult> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(BacTestResult::getDelFlag, 0);
                    if (ToolsUtils.isNotEmpty(bacDrugTestResult.getSampleda())) {
                        Timestamp timestamp = new Timestamp(bacDrugTestResult.getSampleda().getTime());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String formattedDate = sdf.format(timestamp);
                        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
                        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
                        queryWrapper.ge(BacTestResult::getSampleda, startTime);
                        queryWrapper.le(BacTestResult::getSampleda, endTime);
                    }
                    queryWrapper.eq(BacTestResult::getIsolateNum, bacDrugTestResult.getIsolateNum());
                    queryWrapper.eq(BacTestResult::getGermNo, bacDrugTestResult.getGermNo());
                    queryWrapper.eq(BacTestResult::getRptGroup, bacDrugTestResult.getRptGroup());
                    queryWrapper.eq(BacTestResult::getSampleNo, bacDrugTestResult.getSampleNo());
                    queryWrapper.eq(ToolsUtils.isNotEmpty(bacDrugTestResult.getTestFlowNo()), BacTestResult::getTestFlowNo, bacDrugTestResult.getTestFlowNo());
                    queryWrapper.eq(ToolsUtils.isNotEmpty(bacDrugTestResult.getTestNodeNo()), BacTestResult::getTestNodeNo, bacDrugTestResult.getTestNodeNo());
                    List<BacTestResult> testResultList = bacTestResultMapper.selectList(queryWrapper);
                    if (ToolsUtils.isNotEmpty(testResultList)) {
                        List<BacDrugTestResult> astResults = new ArrayList<>();
                        astResults.add(bacDrugTestResult);

                        bacBreakPointCalcService.setApplicableBreakpoint(testResultList.get(0), astResults, isCalcBP, isCalcIC);
                    }

                    //计算完折点后需要根据药敏结果敏感性规则判断该药敏是否符合敏感性规则，如果符合则只修改药敏的敏感性
                    judgeResultSenroleRule(bacDrugTestResult,isCalcIC);
                }
            }
        }
        int i = bacDrugTestResultMapper.updateById(bacDrugTestResult);
        if (i > 0) {
            return Result.succ(1, "更新成功", bacDrugTestResult);
        }
        return Result.fail("更新失败");
    }
    @Autowired
    RedisSysParamHelper redisSysParamHelper;
    @Override
    public Result drugResultTemplateQuickInsert(BacDrugResTempQuickInsertRequest input) {
        if (input.getBacDrugResultTemplates().isEmpty()) {
            return Result.fail("请选择药敏模板组合");
        }
        List<String> tempNos = input.getBacDrugResultTemplates().stream().map(BacDrugResultTemplate::getTemplateNo).distinct().collect(Collectors.toList());

        if (tempNos.isEmpty()) {
            return Result.fail("请选择药敏模板组合");
        }

        if (StringUtils.isBlank(input.getRptGroup()) || StringUtils.isBlank(input.getSampleNo()) || BeanUtil.isEmpty(input.getSampleda())) {
            return Result.fail("请选择检验主记录");
        }

        if (StringUtils.isBlank(input.getIsolateNum())) {
            return Result.fail("请选择细菌鉴定结果");
        }

        /*本检验记录已存在的药敏结果*/
        MPJLambdaWrapper<BacDrugTestResult> queryBDTRWrapper = new MPJLambdaWrapper<>();
        queryBDTRWrapper.eq(BacDrugTestResult::getDelFlag, 0);
        queryBDTRWrapper.eq(BacDrugTestResult::getSampleNo, input.getSampleNo())
                .eq(BacDrugTestResult::getSampleda, input.getSampleda())
                .eq(BacDrugTestResult::getRptGroup, input.getRptGroup())
                .eq(BacDrugTestResult::getTestFlowNo, input.getTestFlowNo())
                .eq(BacDrugTestResult::getTestNodeNo, input.getTestNodeNo())
                .eq(BacDrugTestResult::getGermNo, input.getGermNo())
                .eq(BacDrugTestResult::getIsolateNum, input.getIsolateNum());

        queryBDTRWrapper.eq(BacDrugTestResult::getIsolateNum, input.getIsolateNum());
        List<BacDrugTestResult> BacDrugTestResultList = bacDrugTestResultMapper.selectList(queryBDTRWrapper);

        List<String> drugNos = null;

        if (!BacDrugTestResultList.isEmpty()) {
            drugNos = BacDrugTestResultList.stream().map(BacDrugTestResult::getAntNo).collect(Collectors.toList());
        }

        /*药敏模板对应的明细*/
        MPJLambdaWrapper<BacDrugResultTempdetail> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(BacDrugResultTempdetail.class);
        queryWrapper.selectAs("ant", BacAntibioticsDict::getVerificationPrice, BacDrugResultTempdetail::getVerificationPrice);
        queryWrapper.eq(BacDrugResultTempdetail::getDelFlag, 0);
        queryWrapper.in(BacDrugResultTempdetail::getTempldateNo, tempNos);
        queryWrapper.leftJoin(BacAntibioticsDict.class, "ant", p -> p.eq(BacAntibioticsDict::getAntCode, BacDrugResultTempdetail::getAntNo).isNotNull(BacAntibioticsDict::getAntCode).ne(BacAntibioticsDict::getAntCode, ""));
        if (!BeanUtil.isEmpty(drugNos) && !drugNos.isEmpty()) {
            queryWrapper.notIn(BacDrugResultTempdetail::getAntNo, drugNos);
        }

        List<BacDrugResultTempdetail> BacDrugResultTempdetailList = bacDrugResultTempdetailMapper.selectList(queryWrapper);

        List<BacDrugTestResult> insertList = new ArrayList<>();

        for (BacDrugResultTempdetail m : BacDrugResultTempdetailList) {
            List<BacDrugTestResult> isExist = insertList.stream().filter(p -> p.getAntNo().equals(m.getAntNo())).collect(Collectors.toList());
            if (!isExist.isEmpty()) {
                continue;
            }
            BacDrugTestResult op = new BacDrugTestResult();
            op.setIsolateNum(input.getIsolateNum());
            op.setAntNo(m.getAntNo());
            op.setAntNa(m.getAntNa());
            op.setSampleda(input.getSampleda());
            op.setSampleNo(input.getSampleNo());
            op.setRptGroup(input.getRptGroup());
            op.setBreakPoint(m.getBreakPoint());
            op.setTestFlowNo(input.getTestFlowNo());
            op.setTestNodeNo(input.getTestNodeNo());
            op.setGermNo(input.getGermNo());
            op.setR(m.getR());
            op.setI(m.getI());
            op.setS(m.getS());
            op.setSdd(m.getSdd());
            op.setEcoff(m.getEcoff());
            op.setDrugMthNo(m.getAstTestMthDictNo());
            op.setTestResult(m.getDefResult());
            op.setSensitiveNo(m.getInterCodeDictNo());
            op.setVerificationPrice(m.getVerificationPrice());
            op.setPotency(m.getVerificationPrice());
            op.setSeq(m.getSeq()+"");
            op.setDataFrom("2");
            insertList.add(op);
        }
        if (insertList.size() <= 0) {
            return Result.succ(1, "插入成功", null);
        }

        if (true) {
            //先查出上机记录
            String format = DateUtil.format(input.getSampleda(), "yyyy-MM-dd");
            Timestamp startTime1 = Timestamp.valueOf(format + " 00:00:00");
            Timestamp endTime1 = Timestamp.valueOf(format + " 23:59:59");
            LambdaQueryWrapper<LabMaininfo> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(LabMaininfo::getDelFlag, 0)
                    .eq(LabMaininfo::getRptGroup, input.getRptGroup())
                    .ge(LabMaininfo::getSampleda, startTime1)
                    .le(LabMaininfo::getSampleda, endTime1)
                    .eq(LabMaininfo::getSampleNo, input.getSampleNo());
            List<LabMaininfo> maininfoList1 = labMaininfoMapper.selectList(queryWrapper3);

            for (BacDrugTestResult bacDrugTestResult : insertList) {
                String notReportSensitiveNo = null;
                if (ToolsUtils.isNotEmpty(maininfoList1)) {
                    LabMaininfo labMaininfo = maininfoList1.get(0);
                    if(ToolsUtils.isNotEmpty(labMaininfo)){
                        notReportSensitiveNo = judgeDrugNotReport(bacDrugTestResult,labMaininfo);
                    }
                }
                //判断是否符合天然耐药规则
                judgeNaturalMdrRule(bacDrugTestResult);
                Integer isNaturlResis = bacDrugTestResult.getIsNaturlResis();
                //1是天然耐药
                if(!(ToolsUtils.isNotEmpty(isNaturlResis)&&isNaturlResis==1)&&ToolsUtils.isEmpty(notReportSensitiveNo)){
                    //查看此结果是否符合药敏结果敏感性规则
                    String sensitiveNo = judgeSensitiveResultRule(bacDrugTestResult,true);
                    if(ToolsUtils.isEmpty(sensitiveNo)){
                        /*计算折点*/
                        if (ToolsUtils.isNotEmpty(bacDrugTestResult.getDrugMthNo()) && ToolsUtils.isNotEmpty(bacDrugTestResult.getBreakPoint())) {
                            StringBuilder formattedASTResult = new StringBuilder();
                            BigDecimal[] result = new BigDecimal[1];
                            boolean res = bacBreakPointCalcService.transResult(bacDrugTestResult.getTestResult(), formattedASTResult, result);
                            if (res) {
                                /*检测方法*/
                                LambdaQueryWrapper<BacAstTestMthDict> queryWrapper1 = new LambdaQueryWrapper<>();
                                queryWrapper1.eq(BacAstTestMthDict::getDelFlag, 0);
                                queryWrapper1.eq(BacAstTestMthDict::getCode, bacDrugTestResult.getDrugMthNo());
                                List<BacAstTestMthDict> astTestMthDictList = bacAstTestMthDictMapper.selectList(queryWrapper1);
                                if (ToolsUtils.isNotEmpty(astTestMthDictList)) {
                                    /*折点对象*/
                                    BacBreakPoint bacBreakPoint = new BacBreakPoint();
                                    bacBreakPoint.setR(ToolsUtils.isNotEmpty(bacDrugTestResult.getR()) ? bacDrugTestResult.getR().toString() : "");
                                    bacBreakPoint.setS(ToolsUtils.isNotEmpty(bacDrugTestResult.getS()) ? bacDrugTestResult.getS().toString() : "");
                                    bacBreakPoint.setI(ToolsUtils.isNotEmpty(bacDrugTestResult.getI()) ? bacDrugTestResult.getI().toString() : "");
                                    bacBreakPoint.setEcvEcoff(ToolsUtils.isNotEmpty(bacDrugTestResult.getEcoff()) ? bacDrugTestResult.getEcoff().toString() : "");
                                    bacBreakPoint.setSdd(ToolsUtils.isNotEmpty(bacDrugTestResult.getSdd()) ? bacDrugTestResult.getSdd().toString() : "");
                                    BacInterpretationCodeDict ic = bacBreakPointCalcService.getInterpretationCode(astTestMthDictList.get(0), result[0], bacBreakPoint);
                                    if (ic != null) {
                                        bacDrugTestResult.setSensitiveNo(ToolsUtils.isNotEmpty(ic.getCode()) ? ic.getCode() : "");
                                        bacDrugTestResult.setInterpNa(ToolsUtils.isNotEmpty(ic.getName()) ? ic.getName() : "");
                                        bacDrugTestResult.setInterpDisplayColor(ToolsUtils.isNotEmpty(ic.getDisplayColor()) ? ic.getDisplayColor() : "");
                                    }
                                }
                            }
                        }

                    }
                }
            }
            /*查询出细菌结果*/
            LambdaQueryWrapper<BacTestResult> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(BacTestResult::getDelFlag, 0);
            if (ToolsUtils.isNotEmpty(insertList.get(0).getSampleda())) {
                Timestamp timestamp = new Timestamp(insertList.get(0).getSampleda().getTime());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String formattedDate = sdf.format(timestamp);
                Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
                Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
                queryWrapper2.ge(BacTestResult::getSampleda, startTime);
                queryWrapper2.le(BacTestResult::getSampleda, endTime);
            }
            queryWrapper.eq(BacTestResult::getIsolateNum, insertList.get(0).getIsolateNum());
            queryWrapper2.eq(BacTestResult::getGermNo, insertList.get(0).getGermNo());
            queryWrapper2.eq(BacTestResult::getRptGroup, insertList.get(0).getRptGroup());
            queryWrapper2.eq(BacTestResult::getSampleNo, insertList.get(0).getSampleNo());
            queryWrapper2.eq(ToolsUtils.isNotEmpty(insertList.get(0).getTestFlowNo()), BacTestResult::getTestFlowNo, insertList.get(0).getTestFlowNo());
            queryWrapper2.eq(ToolsUtils.isNotEmpty(insertList.get(0).getTestNodeNo()), BacTestResult::getTestNodeNo, insertList.get(0).getTestNodeNo());
            List<BacTestResult> testResultList = bacTestResultMapper.selectList(queryWrapper2);
            if (ToolsUtils.isNotEmpty(testResultList)) {
                List<BacDrugTestResult> collect = insertList.stream().filter(a -> (!(ToolsUtils.isNotEmpty(a.getIsNaturlResis()) && a.getIsNaturlResis() == 1))).collect(Collectors.toList());
                if(ToolsUtils.isNotEmpty(collect)){
                    bacBreakPointCalcService.setApplicableBreakpoint(testResultList.get(0), collect, true, true);
                }
            }
        }

        boolean r = this.saveBatch(insertList);

        return r ? Result.succ(1, "插入成功", insertList) : Result.fail("插入失败");
    }
}
